<template>
  <div class="events-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1>活动中心</h1>
        <p>丰富多彩的康养活动，助您享受精彩生活</p>
      </div>
    </div>

    <!-- 活动列表 -->
    <div class="events-container" v-loading="loading">
      <!-- 筛选栏 -->
      <div class="filter-bar">
        <div class="filter-tags">
          <el-tag v-for="category in categories" :key="category.value"
            :effect="currentCategory === category.label ? 'dark' : 'plain'"
            :type="currentCategory === category.label ? 'primary' : ''" @click="handleCategoryClick(category.label)"
            style="cursor: pointer">
            {{ category.label }}
          </el-tag>
        </div>
        <div class="search-box">
          <el-input v-model="searchKeyword" placeholder="搜索活动..." :prefix-icon="Search" clearable
            class="search-input" />
        </div>
      </div>

      <!-- 活动分组 -->
      <div v-for="(events, month) in groupedEvents" :key="month" class="month-section">
        <h2 class="month-title">{{ month }}</h2>
        <div class="events-grid">
          <div v-for="event in events" :key="event.id" class="event-card" :class="{ ended: isEventEnded(event.date) }"
            @click="$router.push(`/event/${event.id}`)">
            <!-- 活动图片 -->
            <div class="event-image" style="height: 300px">
              <el-image v-if="event.image_url && event.image_url.length > 0"
                :src="'http://localhost:3000' + event.image_url[0]" fit="cover" style="height: 100%; width: 100%">
                <template #placeholder>
                  <div class="image-placeholder">
                    <el-icon>
                      <Picture />
                    </el-icon>
                  </div>
                </template>
              </el-image>
              <div v-else class="no-image-placeholder">
                <el-icon>
                  <Picture />
                </el-icon>
                <span>暂无图片</span>
              </div>
              <div class="image-count" v-if="event.image_url && event.image_url.length > 1">
                <el-icon>
                  <Picture />
                </el-icon>
                {{ event.image_url.length }}
              </div>
            </div>

            <!-- 活动日期 -->
            <div class="event-date" :class="{ 'is-ended': isEventEnded(event.date) }">
              <span class="day">{{ formatDay(event.date) }}</span>
              <span class="month">{{ formatMonth(event.date) }}</span>
            </div>

            <!-- 活动内容 -->
            <div class="event-content">
              <div class="event-status ongoing" v-if="!isEventEnded(event.date)">进行中</div>
              <h3>{{ event.name }}</h3>
              <p class="description">{{ event.description }}</p>
              <div class="event-info">
                <span class="location">
                  <el-icon>
                    <Location />
                  </el-icon>
                  {{ event.location }}
                </span>
              </div>
              <div class="event-action">
                <el-button v-if="!isEventEnded(event.date) && !event.isRegistered" type="primary" size="small"
                  @click.stop="handleRegister(event.id)">
                  立即报名
                </el-button>
                <span v-else-if="event.isRegistered" class="registered-text">
                  <el-icon>
                    <Check />
                  </el-icon>
                  已报名
                </span>
                <span v-else class="ended-text">活动已结束</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
          :current-page="currentPage" @current-change="handlePageChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getEventsWithRegistration, registerEvent } from '@/api/events'
import { ElMessage } from 'element-plus'
import { Location, Timer, Star, User, Check, Picture, Search } from '@element-plus/icons-vue'

const events = ref([])
const loading = ref(false)
const currentCategory = ref('全部活动')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 定义分类选项
const categories = [
  { label: '全部活动', value: 'all' },
  { label: '康养活动', value: 'health', keywords: ['康养', '健康', '养生', '保健'] },
  { label: '文娱活动', value: 'entertainment', keywords: ['文化', '娱乐', '艺术', '表演', '音乐'] },
  { label: '户外活动', value: 'outdoor', keywords: ['户外', '运动', '游览', '参观'] },
  { label: '公益活动', value: 'charity', keywords: ['公益', '志愿', '服务'] },
  { label: '学习活动', value: 'education', keywords: ['学习', '讲座', '培训', '教育'] }
]

// 筛选后的活动列表
const filteredEvents = computed(() => {
  let filtered = events.value

  // 先按分类筛选
  if (currentCategory.value !== '全部活动') {
    const category = categories.find(cat => cat.label === currentCategory.value)
    if (category) {
      filtered = filtered.filter(event => {
        const searchText = [
          event.name || '',
          event.description || '',
          event.location || '',
          event.type || '',
          event.category || ''
        ].join(' ').toLowerCase()
        return category.keywords.some(keyword => searchText.includes(keyword))
      })
    }
  }

  // 再按搜索关键词筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase().trim()
    filtered = filtered.filter(event => {
      return event.name?.toLowerCase().includes(keyword) ||
        event.description?.toLowerCase().includes(keyword) ||
        event.location?.toLowerCase().includes(keyword)
    })
  }

  // 更新总数
  total.value = filtered.length

  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 获取当前日期
const today = new Date()
today.setHours(0, 0, 0, 0)

// 按日期排序并分组的活动列表
const groupedEvents = computed(() => {
  const activeEvents = []
  const endedEvents = []

  // 使用 filteredEvents 而不是 events
  filteredEvents.value.forEach((event) => {
    const eventDate = new Date(event.date)
    eventDate.setHours(23, 59, 59, 999)
    if (eventDate < today) {
      endedEvents.push(event)
    } else {
      activeEvents.push(event)
    }
  })

  // 未结束的活动按日期正序（近期在前）
  activeEvents.sort((a, b) => new Date(a.date) - new Date(b.date))
  // 已结束的活动按日期倒序
  endedEvents.sort((a, b) => new Date(b.date) - new Date(a.date))

  // 合并两组活动，已结束的放在最后
  const sortedEvents = [...activeEvents, ...endedEvents]

  // 按月份分组
  const groups = {}
  sortedEvents.forEach((event) => {
    const date = new Date(event.date)
    const monthKey = date.toLocaleString('zh-CN', { year: 'numeric', month: 'long' })
    if (!groups[monthKey]) {
      groups[monthKey] = []
    }
    groups[monthKey].push(event)
  })

  return groups
})

// 检查活动是否已结束
const isEventEnded = (date) => {
  const eventDate = new Date(date)
  eventDate.setHours(23, 59, 59, 999)
  return eventDate < today
}

const fetchEvents = async () => {
  loading.value = true
  try {
    const response = await getEventsWithRegistration()
    events.value = response.data
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败')
  } finally {
    loading.value = false
  }
}

const handleRegister = async (eventId) => {
  try {
    await registerEvent(eventId)
    // 重新获取活动列表以更新数据
    await fetchEvents()
    ElMessage.success('活动报名成功')
  } catch (error) {
    console.error('活动报名失败:', error)
    ElMessage.error(error.response?.data?.message || '活动报名失败')
  }
}

const formatDay = (dateString) => {
  return new Date(dateString).getDate()
}

const formatMonth = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN', { month: 'short' })
}

const formatTime = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
  })
}

// 处理分类点击
const handleCategoryClick = (category) => {
  currentCategory.value = category
}

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

onMounted(() => {
  fetchEvents()
})
</script>

<style scoped>
.page-header {
  background: linear-gradient(135deg, #20b2aa, #3498db);
  color: white;
  padding: 60px 20px;
  text-align: center;
  margin-bottom: 40px;
  position: relative;
  overflow: hidden;
}

.page-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('/pattern.png') repeat;
  opacity: 0.1;
}

.header-content {
  max-width: 800px;
  margin: 0 auto;
  position: relative;
}

.header-content h1 {
  font-size: 2.8em;
  margin-bottom: 15px;
  font-weight: 600;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
}

.header-content p {
  font-size: 1.3em;
  opacity: 0.9;
  margin-bottom: 30px;
}

.events-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px 40px;
}

.filter-bar {
  margin: 0 auto 40px;
  max-width: 1000px;
  padding: 16px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24px;
  box-shadow:
    0 10px 30px rgba(0, 0, 0, 0.04),
    0 0 1px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.7);
}

.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
  padding: 8px;
  margin-bottom: 16px;
}

.search-box {
  width: 300px;
  margin-left: auto;
  padding: 0 8px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  background: rgba(255, 255, 255, 0.9);
  padding-left: 16px;
  padding-right: 16px;
  height: 44px;
}

.search-input :deep(.el-input__inner) {
  font-size: 15px;
  color: #333;
}

.search-input :deep(.el-input__inner::placeholder) {
  color: #999;
}

.search-input :deep(.el-input__prefix) {
  font-size: 18px;
  color: #666;
}

.filter-tags .el-tag {
  cursor: pointer;
  transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
  height: 44px;
  line-height: 44px;
  padding: 0 24px;
  font-size: 15px;
  border-radius: 22px;
  border: none;
  background: #e8f4ff;
  color: #4a90e2;
  font-weight: 500;
  position: relative;
  overflow: hidden;
  box-shadow: inset 0 0 0 1px rgba(74, 144, 226, 0.1);
}

.filter-tags .el-tag::before {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(120deg, transparent, rgba(255, 255, 255, 0.8), transparent);
  transform: translateX(-100%);
  transition: transform 0.5s ease;
}

.filter-tags .el-tag:hover {
  transform: translateY(-2px);
  background: #d1e8ff;
  color: #2171c7;
  box-shadow:
    0 4px 12px rgba(74, 144, 226, 0.15),
    inset 0 0 0 1px rgba(74, 144, 226, 0.2);
}

.filter-tags .el-tag.el-tag--primary {
  background: linear-gradient(135deg, #4a90e2, #357abd);
  color: white;
  font-weight: 600;
  box-shadow:
    0 4px 15px rgba(74, 144, 226, 0.3),
    inset 0 0 0 1px rgba(255, 255, 255, 0.2);
}

.filter-tags .el-tag.el-tag--primary::after {
  content: '';
  position: absolute;
  inset: 0;
  background: linear-gradient(120deg,
      rgba(255, 255, 255, 0.2),
      rgba(255, 255, 255, 0.4),
      rgba(255, 255, 255, 0.1));
  opacity: 0;
  transition: opacity 0.3s ease;
}

.filter-tags .el-tag.el-tag--primary:hover {
  transform: translateY(-2px);
  background: linear-gradient(135deg, #357abd, #2171c7);
  box-shadow:
    0 6px 20px rgba(74, 144, 226, 0.4),
    inset 0 0 0 1px rgba(255, 255, 255, 0.3);
}

.sort-options {
  display: flex;
  align-items: center;
  gap: 10px;
}

.sort-label {
  color: #666;
}

.events-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 30px;
}

.event-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
}

.event-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.event-image {
  height: 200px;
  position: relative;
  overflow: hidden;
  background: #f5f7fa;
}

.no-image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 16px;
  gap: 10px;
}

.no-image-placeholder .el-icon {
  font-size: 40px;
  opacity: 0.5;
}

.no-image-placeholder span {
  opacity: 0.7;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  color: #909399;
  font-size: 24px;
}

.image-count {
  position: absolute;
  right: 10px;
  bottom: 10px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.event-date {
  position: absolute;
  top: 20px;
  left: 20px;
  background: var(--el-color-primary);
  color: white;
  padding: 10px 15px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.event-date.is-ended {
  background: #909399;
}

.event-date .day {
  font-size: 1.8em;
  font-weight: 600;
  line-height: 1;
  display: block;
}

.event-date .month {
  font-size: 1em;
  margin-top: 4px;
  display: block;
}

.event-content {
  padding: 20px;
  position: relative;
}

.event-status {
  position: absolute;
  top: -12px;
  right: 20px;
  background: #909399;
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
}

.event-status.ongoing {
  background: var(--el-color-success);
}

.event-content h3 {
  font-size: 1.3em;
  color: #2c3e50;
  margin-bottom: 10px;
  padding-right: 80px;
}

.description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.event-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 15px;
}

.event-info span {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 0.9em;
}

.event-action {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.event-action .el-button {
  padding: 10px 24px;
  font-size: 15px;
  font-weight: 500;
  border: none;
  background: linear-gradient(135deg, var(--el-color-primary), var(--el-color-primary-light-3));
  box-shadow:
    0 4px 12px rgba(var(--el-color-primary-rgb), 0.3),
    inset 0 2px 4px rgba(255, 255, 255, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.event-action .el-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(120deg,
      transparent,
      rgba(255, 255, 255, 0.3),
      transparent);
  transition: 0.5s;
}

.event-action .el-button:hover {
  transform: translateY(-2px);
  box-shadow:
    0 6px 20px rgba(var(--el-color-primary-rgb), 0.4),
    inset 0 2px 4px rgba(255, 255, 255, 0.4);
}

.event-action .el-button:hover::before {
  left: 100%;
}

.event-action .el-button:active {
  transform: translateY(0);
  box-shadow:
    0 2px 8px rgba(var(--el-color-primary-rgb), 0.3),
    inset 0 1px 2px rgba(255, 255, 255, 0.2);
}

.registered-text {
  color: var(--el-color-success);
  font-size: 0.95em;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  background: var(--el-color-success-light-9);
  padding: 8px 16px;
  border-radius: 20px;
  box-shadow:
    0 2px 8px rgba(var(--el-color-success-rgb), 0.1),
    inset 0 0 0 1px rgba(var(--el-color-success-rgb), 0.1);
}

.registered-text .el-icon {
  font-size: 16px;
  background: var(--el-color-success-light-8);
  padding: 4px;
  border-radius: 50%;
}

.ended-text {
  color: #909399;
  font-size: 0.95em;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  background: var(--el-color-info-light-9);
  padding: 8px 16px;
  border-radius: 20px;
  box-shadow:
    0 2px 8px rgba(144, 147, 153, 0.1),
    inset 0 0 0 1px rgba(144, 147, 153, 0.1);
}

.month-section {
  margin-bottom: 40px;
}

.month-title {
  color: #2c3e50;
  font-size: 1.5em;
  margin-bottom: 20px;
  padding-left: 20px;
  position: relative;
}

.month-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 20px;
  background: var(--el-color-primary);
  border-radius: 2px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

.search-input {
  width: 100%;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  background: rgba(255, 255, 255, 0.9);
  padding-left: 16px;
  padding-right: 16px;
  height: 44px;
}

.search-input :deep(.el-input__inner) {
  font-size: 15px;
  color: #333;
}

.search-input :deep(.el-input__inner::placeholder) {
  color: #999;
}

.search-input :deep(.el-input__prefix) {
  font-size: 18px;
  color: #666;
}

@media (max-width: 768px) {
  .page-header {
    padding: 40px 20px;
  }

  .header-content h1 {
    font-size: 2em;
  }

  .events-grid {
    grid-template-columns: 1fr;
  }

  .filter-bar {
    padding: 12px;
    margin: 0 15px 30px;
    border-radius: 20px;
  }

  .filter-tags {
    gap: 8px;
    padding: 4px;
    margin-bottom: 12px;
  }

  .search-box {
    width: 100%;
    margin-left: 0;
    padding: 4px;
  }

  .event-card {
    flex-direction: column;
  }

  .event-date {
    position: relative;
    top: 0;
    left: 0;
    width: fit-content;
    margin: -30px auto 10px;
  }

  .filter-tags .el-tag {
    height: 38px;
    line-height: 38px;
    padding: 0 18px;
    font-size: 14px;
    border-radius: 19px;
  }

  .event-action {
    margin-top: 12px;
  }

  .event-action .el-button {
    padding: 8px 20px;
    font-size: 14px;
  }

  .registered-text,
  .ended-text {
    font-size: 0.9em;
    padding: 6px 14px;
  }

  .registered-text .el-icon {
    font-size: 14px;
    padding: 3px;
  }
}
</style>
